#region References
using Microsoft.CommerceServer.Interop.Configuration;
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
#endregion

namespace CommerceServerTools
{
	/// <summary>
	/// Command Line Access to the Commerce Server Site Packager Script Database Table
	/// </summary>
	/// <remarks>
	/// Built and tested with Commerce Server 2002 Service Pack 3 / Feature Pack 1
	/// </remarks>
	class PupScriptManager
	{
		#region Data Members
		private static OperationType Operation;
		private static string SiteName, ResourceName, ScriptName, ScriptFilename;
		#endregion
		
		/// <summary>
		/// Application Mainline
		/// </summary>
		/// <param name="args">Command Line Arguments</param>
		/// <returns>Returns zero if the operation was successful; otherwise an integer indicating the type of problem.</returns>
		/// <exception cref="COMException">
		/// Thrown if there was a problem interacting with
		/// the Commerce Server objects.  See "Standard COM Errors" in the Commerce Server
		/// documentation for additional details.
		/// </exception>
		[STAThread]
		static int Main(string[] args)
		{
			if(!ParseArguments(args))
			{
				DisplayHelp();
				return ErrorLevel.InvalidCommandLineArguments;
			}

			try
			{
				// Connect to the MSCS Administration Database.
				SiteConfig SiteConfigObject = new SiteConfigClass();
				SiteConfigObject.Initialize(SiteName);

				// Perform the requested operation.
				switch(Operation)
				{
					case OperationType.Delete:
						SiteConfigObject.DeleteSQLScript(ResourceName, ScriptName);
						break;
					case OperationType.Get:					
						Console.WriteLine(SiteConfigObject.GetSQLScript(ResourceName, ScriptName));
						break;
					case OperationType.Put:					
						string ScriptContents = null;
						StreamReader FileStream = new StreamReader(ScriptFilename);

						try
						{
							ScriptContents = FileStream.ReadToEnd();						
						}
						finally
						{
							if( FileStream != null )
								FileStream.Close();
						}

						if(ScriptContents != null)
							SiteConfigObject.PutSQLScript(ResourceName, ScriptName, ScriptContents);
						else
							return ErrorLevel.NullScriptContents;
					
						break;
				}
			} 
			catch (COMException ex)
			{
				Console.Error.WriteLine(ex.ToString());
				return ErrorLevel.COMExceptionThrown;
			}
			
			return ErrorLevel.Success;
		}

		/// <summary>
		/// Parses the arguments.
		/// </summary>
		/// <param name="args">Array of strings containing the console application arguments.</param>
		static bool ParseArguments(string[] args)
		{
			if( (args.Length < 4) || (args.Length > 5) )
				return false;

			string enumValue = args[0];
			if( String.Compare(enumValue, "-d", true, CultureInfo.InvariantCulture) == 0 )
				Operation = OperationType.Delete;
			else if( String.Compare(enumValue, "-g", true, CultureInfo.InvariantCulture) == 0 )
				Operation = OperationType.Get;
			else if( ( String.Compare(enumValue, "-p", true, CultureInfo.InvariantCulture) == 0 ) &&
				     ( args.Length == 5 ))
			{
				Operation = OperationType.Put;
				ScriptFilename = args[4];
			}
			else
				return false;
			
			SiteName = args[1];
			ResourceName = args[2];
			ScriptName = args[3];

			return true;
		}

		/// <summary>
		/// Displays the help.
		/// </summary>
		static void DisplayHelp()
		{
			Version AppVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

			Console.WriteLine("Commerce Server 2002 Site Packager Script Manager v{0}.{1}.{2}.{3}", AppVersion.Major, AppVersion.Minor, AppVersion.Build, AppVersion.Revision);
			Console.WriteLine("- Colin Bowern <colinbowern@hotmail.com>");
			Console.WriteLine("");
			Console.WriteLine("PupScriptManager.exe [-d|-g|-p] site_name resource_name script_name [script_file]");
			Console.WriteLine("");
			Console.WriteLine(" Operations:");
			Console.WriteLine("     -d - Delete Script");
			Console.WriteLine("     -g - Get Script");
			Console.WriteLine("     -p - Put Script");
			Console.WriteLine("");
			Console.WriteLine(" site_name     - Name of the site as seen in Commerce Server Manager");
			Console.WriteLine(" resource_name - Name of the resource.");
			Console.WriteLine(" script_name   - Name of the script in the pupdbscripts table in the Administration database.");
			Console.WriteLine(" script_file   - File containing the script to be put in the database (Put Script operation only).");
		}
	}

	#region Data Types
	/// <summary>
	/// Operation Types
	/// </summary>
	internal enum OperationType
	{
		Delete,
		Get,
		Put
	}

	/// <summary>
	/// Error Levels
	/// </summary>
	internal struct ErrorLevel
	{
		public const int Success = 0;
		public const int InvalidCommandLineArguments = 1;
		public const int NullScriptContents = 2;
		public const int COMExceptionThrown = 3;
	}
	#endregion
}
